import { Controller, Get, Query, Post, Body } from '@nestjs/common'
import { provinceArr } from './province'
import { InjectRepository } from '@nestjs/typeorm'
import { ProvinceEntity } from 'src/entities/province.entity'
import { Repository } from 'typeorm'
import { ApiTags, ApiOperation, ApiProperty, ApiBody } from '@nestjs/swagger'

class cQuery {
  @ApiProperty()
  parentCode: string
}

class resultData {
  parentCode: string
  name: string
  code: string
}

@Controller('pcas')
@ApiTags('省市县镇')
export class ProvincesController {
  private province = null
  constructor(
    @InjectRepository(ProvinceEntity)
    private readonly provinceRepository: Repository<ProvinceEntity>,
  ) {}

  @Get('/all')
  @ApiOperation({ summary: '省市县镇树' })
  async findProvince(): Promise<any> {
    if (!this.province) {
      this.province = this.arr2Tree(await this.provinceRepository.find(), {
        code: '0',
      })
    }
    return this.province
  }

  @Get('/city')
  @ApiOperation({ summary: '获取市/县（区）/镇 （省默认code为0）' })
  async findCity(@Query() query: cQuery): Promise<Array<resultData>> {
    return await this.provinceRepository.find({
      where: { parentCode: query.parentCode },
    })
  }

  @Post('/add')
  @ApiOperation({ summary: '导入省市区数据' })
  async addData(): Promise<any> {
    let dataArr: Array<ProvinceEntity> = []
    provinceArr.forEach(i => {
      let item = new ProvinceEntity()
      item.name = i[0]
      item.code = i[1]
      if (i[1].indexOf('00') === 2) {
        item.parentCode = '0'
      } else if (i[1].indexOf('00') === 4) {
        item.parentCode = i[1].slice(0, 2) + '0000'
      } else {
        item.parentCode = i[1].slice(0, 4) + '00'
      }
      dataArr.push(item)
    })
    const [err, result] = await this.provinceRepository.save(dataArr)
    if (err) return err
    return result
  }

  arr2Tree(data: any[], root: ProvinceEntity | any): any {
    const res: ProvinceEntity[] = []
    data.forEach(item => {
      if (item.parentCode === root.code) {
        const children = this.arr2Tree(data, item)
        if (children.length) item.children = children
        res.push(item)
      }
    })
    return res
  }
}
